package dao;

import java.util.Map;

import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

import po.Account;
import po.Cart;
import service.CartService;
import service.impl.CartServiceImpl;

/**
 * Application Lifecycle Listener implementation class SessionListener
 *
 */
public class SessionListener implements HttpSessionListener {
	private CartService cartService = new CartServiceImpl();
    /**
     * Default constructor. 
     */
    public SessionListener() {
        // TODO Auto-generated constructor stub
    }

    public void sessionCreated(HttpSessionEvent arg0)  { 
    	
    }

    public void sessionDestroyed(HttpSessionEvent arg0)  { 
    	HttpSession session = arg0.getSession();
    	Map<Integer, Integer> carts = (Map<Integer, Integer>) session.getAttribute("carts");
    	Account account = (Account)session.getAttribute("account");
    	Cart cart = null;
    	if(account != null && carts != null){
    		String aid = account.getAid();
    		for(Integer i : carts.keySet()){
    			cart = new Cart();
    			cart.setAid(aid);
    			cart.setDid(i);
    			cart.setCount(carts.get(i));
    			cartService.addCart(cart);
    		}
    		
    	}
    }
	
}
